package com.example.myapplication;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class RateListActivity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 先设置空列表避免白屏
        setListAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<>()));

        // 启动异步任务获取数据
        new FetchRateTask().execute();
    }

    private class FetchRateTask extends AsyncTask<Void, Void, List<String>> {
        @Override
        protected List<String> doInBackground(Void... voids) {
            List<String> rateList = new ArrayList<>();

            try {
                // 获取网页文档
                Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/")
                        .timeout(10000)
                        .get();

                // 定位汇率表格（根据实际网页结构调整选择器）
                Elements rows = doc.select(".BOC_main table tr");

                for (Element row : rows) {
                    Elements cols = row.select("td");
                    if (cols.size() >= 8) { // 确认列数
                        String currency = cols.get(0).text();    // 货币名称
                        String cashBuy = cols.get(1).text();    // 现汇买入价
                        String cashSell = cols.get(3).text();   // 现汇卖出价

                        // 格式化显示内容
                        rateList.add(currency + "\n现汇买入: " + cashBuy + "  现汇卖出: " + cashSell);
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                rateList.add("数据加载失败，请检查网络连接");
            }

            return rateList;
        }

        @Override
        protected void onPostExecute(List<String> result) {
            super.onPostExecute(result);
            // 更新UI
            ArrayAdapter<String> adapter = new ArrayAdapter<>(
                    RateListActivity.this,
                    android.R.layout.simple_list_item_1,
                    result
            );
            setListAdapter(adapter);
        }
    }
}